package com.crr.controller;

import com.crr.apis.PayFeignApi;
import com.crr.ret.ResultData;
import io.github.resilience4j.bulkhead.annotation.Bulkhead;
import io.github.resilience4j.circuitbreaker.annotation.CircuitBreaker;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

@RestController
public class OrderCircuitController {
    @Resource
    private PayFeignApi payFeignApi;

    @CircuitBreaker(name = "cloud-payment-service", fallbackMethod = "myCircuitFallback")
    @GetMapping("/feign/pay/circuit/{id}")
    public ResultData<String> myCircuitBreaker(@PathVariable("id") Integer id) {
        return payFeignApi.myCircuit(id);
    }

    public ResultData<String> myCircuitFallback(Throwable t) {
        return ResultData.fail("500","myCircuitBreaker ,系统繁忙，请稍后重试");
    }

    /**
     * 舱壁隔离 semaphore 信号量
     * @param id
     * @return
     */
/*    @Bulkhead(name = "cloud-payment-service", fallbackMethod = "myBulkHeadFallback",type = Bulkhead.Type.SEMAPHORE )
    @GetMapping("/feign/pay/bulkhead/{id}")
    public ResultData<String> myBulkHeadSemaphore(@PathVariable("id") Integer id) {
        return payFeignApi.myCircuit(id);
    }

    public ResultData<String> myBulkHeadFallback(Throwable t) {
        return ResultData.fail("500","myBUlkHead ,隔板超出最大数量限制 ,系统繁忙，请稍后重试");
    }*/

    /**
     * 舱壁隔离 threadpool线程池
     * @param id
     * @return
     */
        @Bulkhead(name = "cloud-payment-service", fallbackMethod = "myBulkHeadFallback",type = Bulkhead.Type.THREADPOOL)
        @GetMapping("/feign/pay/bulkhead/{id}")
        public CompletableFuture<String> myBulkHeadThreadPool(@PathVariable("id") Integer id) {
            System.out.println(Thread.currentThread().getName()+"-------开始进入");
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"----准备离开");
            return CompletableFuture.supplyAsync(()->
                payFeignApi.myBulkHead(id)+"\t"+"Bulkhead.Type.THREADPOOL"
            );
        }

    public CompletableFuture<String> myBulkHeadFallback(Integer id,Throwable t) {
        return CompletableFuture.supplyAsync(()->
           "myBUlkHead ,隔板超出最大数量限制 ,系统繁忙，请稍后重试"+id
        );
    }

    @CircuitBreaker(name = "cloud-payment-service", fallbackMethod = "myRatelimiterFallback")
    @GetMapping("/feign/pay/rateLimit/{id}")
    public ResultData<String> myRatelimiter(@PathVariable("id") Integer id) {
        return payFeignApi.myCircuit(id);
    }

    public ResultData<String> myRatelimiterFallback(Throwable t) {
        return ResultData.fail("500"," myRatelimiterFallback ,你被限流了，禁止访问");
    }
}
